<template>
  <div class="edit-page-wrap">
    <Head title="基础信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="edit-form-wrap"
        >
          <el-form-item label="归属企业" prop="orgId">
            <qc-select
              v-if="!id"
              :value="ruleForm.orgId"
              :remote="true"
              :filterable="true"
              :options="optionsS.org"
              placeholder="请选择归属企业"
              @change="handleChangeOrg"
            >
            </qc-select>
            <div v-else>{{ ruleForm.orgName }}</div>
          </el-form-item>
          <el-form-item label="用户姓名" prop="userName">
            <el-input
              v-model.trim="ruleForm.userName"
              placeholder="请输入用户姓名"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item
            v-if="!id"
            label="用户账号"
            prop="accountNumber"
            class="has-tips"
          >
            <el-input
              v-model.trim="ruleForm.accountNumber"
              placeholder="请输入用户账号"
              maxlength="30"
              clearable
            />
            <div class="tip">
              <div class="icon"></div>
              账号可由数字、字母组合，必须含字母，示例：zhangsan，zs1
            </div>
          </el-form-item>
          <el-form-item v-else label="用户账号">
            <div>{{ ruleForm.accountNumber }}</div>
          </el-form-item>
          <el-form-item v-if="!id" label="密码" prop="password">
            <el-input
              v-model.trim="ruleForm.password"
              placeholder="请输入密码"
              maxlength="30"
              show-password
              clearable
            />
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input
              v-model.trim="ruleForm.mobile"
              placeholder="请输入手机号"
              maxlength="11"
              clearable
            />
          </el-form-item>
          <el-form-item label="用户卡号" prop="cardNo">
            <qc-select
              :value="ruleForm.chargingDTO.cardNum"
              :remote="true"
              :filterable="true"
              :options="optionsS.card"
              placeholder="请输入关键字"
              @change="handleChangeCard"
            >
            </qc-select>
          </el-form-item>
          <el-form-item label="归属城市" prop="cityCodes">
            <el-cascader
              ref="cityRef"
              popper-class="qc-cascader"
              v-model="ruleForm.cityCodes"
              :options="optionsS.city"
              @change="handleChangeCity"
              placeholder="请选择归属城市"
              clearable
            />
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div v-show="ruleForm.orgId" class="edit-line"></div>
    <Head v-show="ruleForm.orgId" title="车辆信息">
      <template #content>
        <Combination
          ref="comCarRef"
          :items="comItem"
          :comData="ruleForm.carDTOList"
          :rules="comRules"
          :btnDisabled="true"
          :hideRequired="true"
          keyBtn="btn"
          @data-minus="dataMinus"
        ></Combination>
      </template>
    </Head>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
    <DialogCar
      ref="dialogCarRef"
      @car-info="carInfo"
      :orgId="ruleForm.orgId"
      :userId="ruleForm.id"
    ></DialogCar>
  </div>
</template>

<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus';
import Head from '@/components/head/index.vue';
import Combination from '@/components/combination/combination.vue';
import DialogCar from '../components/dialogCar.vue';
import { getCity, getMd5 } from '@/utils/utils';
import { addUser, updateUser, queryUserDetail } from '@/service/apis/user';
import { queryAllCompany } from '@/service/apis/org';
import { queryAllChargeCard } from '@/service/apis/pile';
import { queryCompanyDetail } from '@/service/apis/enterprise';
import { IS_PHONE_NUM, IS_NUM_AND_EN } from '@/utils/verify';

const router = useRouter();
const route = useRoute();
const {
  query: { id, cityCode },
} = route;
const ruleFormRef = ref<FormInstance>();
const dialogCarRef = ref();
const comCarRef = ref();

let optionsS = reactive({
  org: [] as any,
  city: [] as any,
  card: [] as any,
});

// 获取归属运营商
queryAllCompany({ isDefault: false }).then((res: any) => {
  if (res) {
    nextTick(() => {
      optionsS.org = [...res.listMap];
    });
  }
});

// 获取省市
getCity().then((res: any) => {
  optionsS.city = res;
});

// 获取充电卡数据
queryAllChargeCard({}).then((res: any) => {
  if (res) {
    optionsS.card = [...res.listMap];
  }
});

//
const queryEnterpriseDetail = () => {
  queryCompanyDetail({ id: ruleForm.orgId }).then((res: any) => {
    ruleForm.cityCodes = [res.provinceCode, res.cityCode];
    ruleForm.cityCode = res.cityCode;
    ruleForm.provinceCode = res.provinceCode;
    ruleForm.cityName = res.cityName;
  });
};

let ruleForm: any = reactive({
  id: '',
  orgId: undefined as unknown,
  orgName: '',
  userName: '',
  accountNumber: '',
  password: '',
  mobile: '',
  chargingDTO: {
    cardNum: undefined as unknown,
  },
  cityName: '',
  cityCode: '',
  provinceCode: '',
  cityCodes: [] as any,
  carDTOList: [] as any,
});

const rules = reactive<FormRules>({
  orgId: [
    { required: true, message: '请选择归属企业', trigger: ['blur', 'change'] },
  ],
  userName: [{ required: true, message: '请输入用户姓名', trigger: 'blur' }],
  accountNumber: [
    { required: true, message: '请输入用户账号', trigger: 'blur' },
    {
      pattern: IS_NUM_AND_EN,
      message: '请输入正确的用户账号(由字母或数字组成,但必须含有字母)',
      trigger: 'blur',
    },
  ],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: IS_PHONE_NUM,
      message: '请输入正确的手机号',
      trigger: 'blur',
    },
  ],
  cityCodes: [
    { required: true, message: '请选择归属城市', trigger: ['blur', 'change'] },
  ],
});

const setBtnDisabled = (row: any, index: number) => {
  // row.data[index].btn = '已设为默认';
  // ruleForm.carDTOList[index].isDefault = true;
  // row.items[index][1].props.disabled = true;
  row.items.forEach((item: any, inx: number) => {
    if (inx !== index) {
      row.data[inx].btn = '设为默认';
      ruleForm.carDTOList[inx].isDefault = false;
      ruleForm.carDTOList[inx].btn = false;
      item[1].props.disabled = false;
    } else {
      row.data[inx].btn = '已设为默认';
      ruleForm.carDTOList[inx].isDefault = true;
      ruleForm.carDTOList[inx].btn = true;
      item[1].props.disabled = true;
    }
  });
  console.log('row----', row, ruleForm.carDTOList);
};
const comItem = reactive([
  {
    comName: 'input',
    label: '车牌号',
    labelWidth: 120,
    prop: 'plateNumber',
    props: {
      placeholder: '上传行驶证后自动显示',
      disabled: true,
    },
  },
  {
    comName: 'button',
    className: 'button-wrap',
    prop: 'btn',
    width: 100,
    props: {
      value: '设为默认',
      type: 'primary',
      disabled: false,
      click: (index: number, row: any) => {
        if (!row.data[index].plateNumber) {
          return;
        }
        setBtnDisabled(row, index);
      },
    },
  },
  {
    comName: 'button',
    className: 'button-wrap',
    prop: 'btn1',
    width: 100,
    props: {
      value: '添加车辆',
      type: 'primary',
      plain: true,
      click: (index: number, row: any) => {
        console.log('ddd', index, row);
        if (row.data[index].plateNumber) {
          dialogCarRef.value.show(
            index,
            row,
            ruleForm.carDTOList,
            ruleForm.carDTOList[index]
          );
        } else {
          dialogCarRef.value.show(index, row, ruleForm.carDTOList);
        }
      },
    },
  },
]);
const comRules = reactive({
  plateNumber: [{ required: true, message: '请先添加车辆', trigger: 'blur' }],
});

const dataMinus = (index: number, item: any) => {
  if (item.plateNumber) {
    ruleForm.carDTOList.splice(index, 1);
    nextTick(() => {
      if (ruleForm.carDTOList.length === 1) {
        const comData = comCarRef.value?.getData();
        const comItems = comCarRef.value?.getItems();
        comCarRef.value?.setValue(0, 'btn', '已设为默认');
        ruleForm.carDTOList[0].isDefault = true;
        ruleForm.carDTOList[0].btn = true;
        comItems[0][1].props.disabled = true;
      }
    });
  }
};

const handleChangeOrg = (e: any) => {
  ruleForm.orgId = e;
  if (ruleForm.orgId && !ruleForm.cityCode) {
    queryEnterpriseDetail();
  }
};

const handleChangeCard = (e: any) => {
  ruleForm.chargingDTO.cardNum = e;
};

const cityRef = ref();
const handleChangeCity = (e: any) => {
  if (e) {
    ruleForm.cityCodes = e;
    ruleForm.cityCode = e[1];
    ruleForm.provinceCode = e[0];
    const node = cityRef.value.getCheckedNodes()[0];
    ruleForm.cityName = node.pathLabels[1];
  } else {
    ruleForm.cityCodes = [];
    ruleForm.cityCode = '';
    ruleForm.provinceCode = '';
    ruleForm.cityName = '';
  }
};

const back = () => {
  router.go(-1);
};

// 编辑回填数据
if (id) {
  queryUserDetail({
    id: id,
    cityCode: cityCode,
  }).then((res: any) => {
    for (const key in ruleForm) {
      if (res[key]) {
        ruleForm[key] = res[key];
      }
    }
    ruleForm.chargingDTO.cardNum = res.cardNum;
    ruleForm.cityCodes = [res.provinceCode, res.cityCode];
    ruleForm.carDTOList = res.carDTOList.map((item: any, index: number) => {
      nextTick(() => {
        if (item.isDefault) {
          comCarRef.value?.setValue(index, 'btn', '已设为默认');
        } else {
          comCarRef.value?.setValue(index, 'btn', '设为默认');
        }
      });
      return { ...item, btn: item.isDefault };
    });
  });
}

// 车辆信息
const carInfo = (index: number, form: any, row: any, isAdd: boolean) => {
  if (isAdd) {
    if (!ruleForm.carDTOList || ruleForm.carDTOList.length === 0) {
      ruleForm.carDTOList = [];
    }
    const obj = { ...form };
    obj.isDefault = true;
    ruleForm.carDTOList.push(obj);
    setBtnDisabled(row, index);
  } else {
    const obj = { ...form };
    ruleForm.carDTOList[index] = obj;
    // setBtnDisabled(row, index);
  }
};

const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  console.log('submit---', ruleForm);
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate((valid, fields: any) => {
    if (valid) {
      console.log('submit---', ruleForm);
      const form = { ...ruleForm };
      if (id) {
        delete form.password;
        updateUser(form).then((res: any) => {
          emit('clear-cache');
          back();
        });
      } else {
        form.password = getMd5(ruleForm.password);
        addUser(form).then((res: any) => {
          emit('clear-cache');
          back();
        });
      }
    } else {
      for (const key in ruleForm) {
        if (fields[key]) {
          ruleFormRef.value?.scrollToField(key);
          break;
        }
      }
    }
  });
};
</script>

<style lang="scss" scoped>
:deep(.combination-wrap .item-wrap) {
  .el-form-item:first-child .el-form-item__content {
    padding-left: 24px !important;
  }
}
</style>
